#include <iostream>
#include <string>
#include <unistd.h>
#include "mysql.h"

// cgi处理
bool GetQueryString(std::string &query_string)
{
    bool result = false;
    std::string method = getenv("METHOD");
    std::cerr << "query_method:" << method << std::endl;
    if (method == "GET")
    {
        char *getret = getenv("QUERY_STRING");
        if (getret == NULL)
        {
            std::cerr << "GETENV ERROR!" << std::endl;
            return 1;
        }
        query_string = getret;
        result = true;
        std::cerr << "DEBUG GET: " << query_string << std::endl;
    }
    else if (method == "POST")
    {
        char *getret = getenv("CONTENT_LENGTH");
        if (getret == NULL)
        {
            std::cerr << "GETENV ERROR!" << std::endl;
            return 1;
        }
        int len = atoi(getenv("CONTENT_LENGTH"));
        char ch;
        while (len)
        {
            read(0, &ch, 1);
            query_string.push_back(ch);
            len--;
        }
        result = true;
        std::cerr << "DEBUG POST: " << query_string << std::endl;
    }
    else
    {
    }
    return result;
}

bool InsertSql(std::string sql)
{
    MYSQL *conn = mysql_init(nullptr);
    if (nullptr == mysql_real_connect(conn, "127.0.0.1", "http_server", "xsc123456", "http_server", 3306, nullptr, 0))
    {
        std::cerr << "connect error!" << std::endl;
        return 1;
    }
    // 在connec后再设置字符集为utf8
    std::cerr << mysql_set_character_set(conn, "utf8") << std::endl;
    std::cerr << "connect success!" << std::endl;
    std::cerr << "query:" << sql << std::endl;
    int ret = mysql_query(conn, sql.c_str());
    std::cerr << "result: " << ret << std::endl;

    // 关闭数据库链接
    mysql_close(conn);
}

bool CutString(std::string &in, const std::string &sep, std::string &out1, std::string &out2)
{
    size_t pos = in.find(sep);
    if (pos != std::string::npos)
    {
        out1 = in.substr(0, pos);
        out2 = in.substr(pos + sep.size());
        return true;
    }
    else
    {
        return false;
    }
}

using namespace std;

char from_hex(char ch) {
    return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;
}

string url_decode(string text) {
    char h;
    ostringstream escaped;
    escaped.fill('0');

    for (auto i = text.begin(), n = text.end(); i != n; ++i) {
        string::value_type c = (*i);

        if (c == '%') {
            if (i[1] && i[2]) {
                h = from_hex(i[1]) << 4 | from_hex(i[2]);
                escaped << h;
                i += 2;
            }
        } else if (c == '+') {
            escaped << ' ';
        } else {
            escaped << c;
        }
    }

    return escaped.str();
}

int main()
{
    // 获取数据
    std::string query_string;
    if (GetQueryString(query_string))
    {
        // std::string sql = "insert into user (name,password) values(\'王五\',\'ww123456\')";
        // 处理数据
        std::string str1, str2;
        CutString(query_string,"&",str1,str2);
        std::string name, password;
        std::string name_val, passwd_val;
        CutString(str1,"=",name,name_val);
        CutString(str2,"=",password,passwd_val);
        name_val = url_decode(name_val);
        std::string sql = "insert into user (name,password) values(\'" + name_val + "\',\'" + passwd_val + "\')";
        if(InsertSql(sql))
        {
            std::cerr << "Insert success : " << sql << std::endl;
        }
    }
    return 0;
}
